package com.situ.onlinebookstore.back.controller;

import com.situ.onlinebookstore.back.service.UserService;
import com.situ.onlinebookstore.common.vo.Result;
import com.situ.onlinebookstore.common.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController //相当于@Controller与@ResponseBody合并
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;
    @RequestMapping("/search")
    public Result search(Integer page, Integer limit, User user) {
        if (page == null) {
            return Result.ok(userService.search(user));
        } else {
            return Result.ok(userService.searchForPage(page, limit, user));
        }
    }

    @RequestMapping("/edit")
    public Result edit(User user) {
        //1-接收参数
        try {
            //2-参数校验
            if (user.getPhone() != null && !user.getPhone().matches("^1[35-9][0-9]{9}$")) {
                throw new Exception("电话格式不对！");
            }
            //3-调用Service层
            userService.edit(user);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }

    //建号
    @RequestMapping("/add")
    public Result add(User user){
        try {
            //2-参数校验
            if (!user.getUsername().matches("^[a-zA-Z0-9]{3,16}$")) {
                throw new Exception("账号格式错误！");
            }
            if (user.getName()!=null && user.getName().length()>0 && !user.getName().matches("^[\\u4E00-\\u9FA5]{2,10}(·[\\u4E00-\\u9FA5]{2,10}){0,2}$")){
                throw new Exception("姓名格式不对！");
            }
            if (user.getPhone() != null && user.getPhone().length()>0 && !user.getPhone().matches("^1[35-9][0-9]{9}$")) {
                throw new Exception("电话格式不对！");
            }
            //默认密码123
            user.setPassword("123");
            userService.add(user);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }
}
